# coding=utf-8

from . import admin
from flask import request, render_template, jsonify
from app import PAGE_NUM, page_code, util
from dbConnection.MysqlConn import Mysql
import math, time
import sys

reload(sys)
sys.setdefaultencoding('utf8')


# 订单列表
@admin.route('/admin/order_list.html')
@util.admin_login
def order_list():
    md = get_store_list()
    jq = get_jq_list()
    return render_template('admin/pay/order_list.html', md=md, jq=jq)


# 获取订单列表数据
@admin.route('/admin/order_list_post', methods=['post'])
@util.admin_login
def order_list_post():
    parms = ['day', 'num', 'sid', 'mid']
    p = request.values.get('p', default='1')
    c_num = (int(p) - 1) * PAGE_NUM
    maps = {}
    for d in parms:
        maps[d] = request.values.get(d)
    sql = "select o.payTime, o.orderNum, o.payOrderNum, o.price, o.plateNum, m.machineNum, s.storeName FROM car_orders " \
          "AS o LEFT JOIN store AS s ON s.storeId = o.storeId LEFT JOIN car_machine AS m ON m.machineId = o.machineId " \
          "WHERE 1=1"
    sql2 = "select count(o.id) AS con,sum(o.price) as total_money FROM car_orders AS o LEFT JOIN store AS" \
           " s ON s.storeId = o.storeId LEFT JOIN " \
           "car_machine AS m ON m.machineId = o.machineId WHERE 1=1"
    if maps['day']:
        s_str = maps['day'] + ' 00:00:00'
        e_str = maps['day'] + ' 23:59:59'
        sql += " and o.payTime >= '%s' and o.payTime <= '%s'" % (s_str, e_str)
        sql2 += " and o.payTime >= '%s' and o.payTime <= '%s'" % (s_str, e_str)
    if maps['num']:
        sql += " and o.orderNum = '%s'" % maps['num']
        sql2 += " and o.orderNum = '%s'" % maps['num']
    if maps['sid']:
        sql += " and o.storeId = '%s'" % maps['sid']
        sql2 += " and o.storeId = '%s'" % maps['sid']
    if maps['mid']:
        sql += " and o.machineId = '%s'" % maps['mid']
        sql2 += " and o.machineId = '%s'" % maps['mid']
    sql += " order by o.payTime desc limit %d, %d" % (c_num, PAGE_NUM)
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    cont = mysql.getOne(sql2, None)
    mysql.dispose()
    if cont:
        pages = math.ceil(cont['con'] / float(PAGE_NUM))
    else:
        pages = 0
    pages = int(pages)
    route_path = 'get_data'
    if pages > 0:
        html_str = page_code.page_code_html_post(int(p), route_path, pages)
    else:
        html_str = ''
    if res:
        for d in res:
            d['payTime'] = str(d['payTime'])
            d['price'] = str(d['price'])
            if d['storeName'] is None:
                d['storeName'] = ""
            if d['machineNum'] is None:
                d['machineNum'] = ""
        data = {
            'status': 1,
            'res': res,
            'page': html_str,
            'count': cont['con'],
            'total_money': cont['total_money'],
            'p': p
        }
    else:
        data = {
            'status': 2,
            'page': html_str
        }
    return jsonify(data)


# 数据汇总
@admin.route('/admin/data_total.html')
@util.admin_login
def data_total():
    md = get_store_list()
    jq = get_jq_list()
    first_day, eday = util.getMonthFirstDayAndLastDay()
    now_day = util.int_ymd(time.time())
    return render_template('admin/pay/data_total.html', md=md, jq=jq, first_day=first_day, now_day=now_day)


# 获取数据汇总
@admin.route('/admin/data_total_post', methods=['post'])
@util.admin_login
def data_total_post():
    day_str = ''
    parms = ['stime', 'etime', 'mid', 'sid']
    p = request.values.get('p', default='1')
    c_num = (int(p) - 1) * PAGE_NUM
    maps = {}
    for d in parms:
        maps[d] = request.values.get(d)
    sql = "select sum(t.money) as money, m.machineNum, s.storeName FROM car_total AS t LEFT JOIN store AS s ON " \
          "s.storeId = t.storeId LEFT JOIN car_machine AS m ON m.machineId = t.machineId WHERE 1=1"
    sql2 = "select count(*) AS con FROM (select sum(t.money) as money, m.machineNum, s.storeName FROM car_total AS t LEFT JOIN " \
           "store AS s ON s.storeId = t.storeId LEFT JOIN car_machine AS m ON m.machineId = t.machineId WHERE 1=1"
    if maps['stime']:
        day_str += maps['stime']
        sql += " and t.day >= '%s'" % maps['stime']
        sql2 += " and t.day >= '%s'" % maps['stime']
    if maps['etime']:
        if maps['etime'] != maps['stime']:
            if day_str == '':
                day_str += maps['etime']
            else:
                day_str += '_' + maps['etime']
        sql += " and t.day <= '%s'" % maps['etime']
        sql2 += " and t.day <= '%s'" % maps['etime']
    if maps['mid']:
        sql += " and t.machineId = '%s'" % maps['mid']
        sql2 += " and t.machineId = '%s'" % maps['mid']
    if maps['sid']:
        sql += " and t.storeId = '%s'" % maps['sid']
        sql2 += " and t.storeId = '%s'" % maps['sid']
    sql += " group by t.machineId order by money desc limit %d, %d" % (c_num, PAGE_NUM)
    sql2 += " group by t.machineId ) aa"
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    cont = mysql.getOne(sql2, None)
    mysql.dispose()
    if res:
        for d in res:
            d['machineNum'] = d['machineNum'] if d['machineNum'] else '未知'
            if d['storeName'] is None:
                d['storeName'] = ""
    if day_str == '':
        day_str = '截至今日'
    if cont:
        pages = math.ceil(cont['con'] / float(PAGE_NUM))
    else:
        pages = 0
    pages = int(pages)
    route_path = 'get_data'
    if pages > 0:
        html_str = page_code.page_code_html_post(int(p), route_path, pages)
    else:
        html_str = ''
    if res:
        for d in res:
            d['money'] = str(d['money'])
        data = {
            'status': 1,
            'res': res,
            'page': html_str,
            'p': p,
            'day_str': day_str
        }
    else:
        data = {
            'status': 2,
            'page': html_str
        }
    return jsonify(data)


# 获取门店列表
def get_store_list():
    sql = "select storeId, storeName FROM store WHERE status = 1"
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return res


# 获取机器列表
def get_jq_list():
    sql = "select machineId, machineNum FROM car_machine WHERE status = 1"
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return res
